//
//  YAYIAddHospitalViewController.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/16.
//
//

#import "YAYIAddHospitalViewController.h"

#import "YAYIAddHospitalCell.h"
#import "YAYIMyHospitalModel.h"
#import "YAYIChoseHospitalListModel.h"
#import "YAYIActionSheet.h"

#import "YAYIAreaModel.h"


#define YAYIAreaSelectorTag 100
#define YAYIHospitalSelectorTag 200

@interface YAYIAddHospitalViewController () <UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, weak) UITextField *nameTf;
@property (nonatomic, weak) UITextField *areaTf;
@property (nonatomic, weak) UITextField *hospitalTf;
@property (nonatomic, weak) UITextField *typeTf;

// 覆盖层
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, weak) UIView *dateSelectView;
@property (nonatomic, weak) UIDatePicker *datePicker;
@property (nonatomic, weak) UIPickerView *pickerView;


@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, strong) NSMutableArray *typeArray;
// 医院数组
@property (nonatomic, strong) NSMutableArray *hospitalAry;


// 参数
@property (nonatomic, copy) NSString *doctorName;
@property (nonatomic, copy) NSString *hospitalID;
@property (nonatomic, copy) NSString *titleID;

// 地区选择器相关
@property (nonatomic, strong) NSArray *provinces;
@property (nonatomic, strong) NSMutableDictionary *cityDict;
@property (nonatomic, copy) NSString *areaCode;
@property (nonatomic, copy) NSString *areaName;

@property (nonatomic, strong) NSMutableArray *areaArray;

@end

@implementation YAYIAddHospitalViewController

- (NSMutableArray *)hospitalAry
{
    if (nil == _hospitalAry) {
        _hospitalAry = [NSMutableArray array];
        
    }
    return _hospitalAry;
}

- (NSMutableArray *)items
{
    if (nil == _items) {
        _items = [NSMutableArray array];
        [_items addObject:@"地区"];
        [_items addObject:@"医院"];
    }
    return _items;
}

- (NSMutableArray *)typeArray
{
    if (nil == _typeArray) {
        //        _typeArray = @[@"主任医师", @"副主任医师", @"主治医生", @"住院医师", @"其他"];
        _typeArray = [NSMutableArray array];
    }
    return _typeArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"添加医院";
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.separatorColor = YAYIColor(0xE5, 0xE5, 0xE5);
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, -10, 0);
    
    [self setupNav];

}


- (instancetype)initWithStyle:(UITableViewStyle)style
{
    return [super initWithStyle:UITableViewStyleGrouped];
}


- (void)setupNav
{
    NSString *rightBtnTitleStr = @"保存";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:rightBtnTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    
    button.frame = (CGRect){{0, 0}, CGSizeMake(70, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


/**
 * 取消焦点
 */
- (void)resignAllFistResponder
{
    [self.nameTf resignFirstResponder];
    [self.hospitalTf resignFirstResponder];
    [self.typeTf resignFirstResponder];
}


#pragma mark - 获取数据
//- (void)createAreaDataSource
//{
//    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//    
//    NSString *urlStr = @"http://120.27.147.43:8080/ya/site/getLocation";
//    
//    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
//    [mgr GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        NSArray *array = responseObject[@"map"][@"provinces"];
//        self.provinces = array;
//        
//        for (NSDictionary *dic in array) {
//            
//            NSMutableDictionary *cityDict = [NSMutableDictionary dictionary];
//            
//            NSDictionary *areaDict = @{@"province":dic[@"name"], @"citys":cityDict};
//            NSString *areaidStr = dic[@"id"];
//            
//            NSInteger keyValue = [areaidStr integerValue] / 10000;
//            
//            mutableDict[@(keyValue)] = areaDict;
//            // [mutableDict setValue:areaDict forKey:@(keyValue)];
//        }
//        
//        //        NSLog(@"areas:%@", mutableDict);
//        
//        NSArray *cityarray = responseObject[@"data"];
//        int i = 0;
//        for (NSDictionary *dict in cityarray) {
//            
//            i++;
//            if (i > 20) {
////                break;
//            }
//            // 判断id前两位，并且后两位等于0，中间两位不等于0
//            
//            NSInteger areaID = [dict[@"id"] integerValue];
//            
//            if (areaID % 100 == 0) {
//                
//                NSInteger provinceKeyValue = areaID / 10000;
//                NSMutableDictionary *citysDict = mutableDict[@(provinceKeyValue)][@"citys"];
//                
//                // 创建地区dictionary
//                NSMutableArray *areaArray = [NSMutableArray array];
//                NSDictionary *areaDict = @{@"name":dict[@"name"], @"areas":areaArray};
//                
//                NSInteger areaKeyValue = areaID / 100;
//                citysDict[@(areaKeyValue)] = areaDict;
//            }else{
//                
//                // 取出市列表dictionary
//                NSInteger provinceKeyValue = areaID / 10000;
//                NSMutableDictionary *citysDict = mutableDict[@(provinceKeyValue)][@"citys"];
//                
//                // 取出地区列表array
//                NSInteger areaKeyValue = areaID / 100;
//                NSMutableArray *areaArray = citysDict[@(areaKeyValue)][@"areas"];
//                
//                [areaArray addObject:dict];
//            }
//            
//            // NSLog(@"dict:%@ %@ head:%ld", areaidStr ,dict[@"name"], keyValue);
//        }
//        
//        self.cityDict = mutableDict;
//        
//        [self.pickerView reloadAllComponents];
//        
//        NSLog(@"areas:%@", mutableDict);
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
//    
//}


- (void)createAreaDataSource
{
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    NSString *urlStr = @"http://120.27.147.43:8080/ya/site/getLocation";
    
    [mgr GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableArray *areaArray = [NSMutableArray array];
        NSArray *cityarray = responseObject[@"data"];
        int i = 0;
        for (NSDictionary *dict in cityarray) {
            
            i++;
            if (i > 20) {
//                                break;
            }
            
            NSInteger areaID = [dict[@"id"] integerValue];
            if (areaID % 10000 == 0) { // 省
                
                YAYIAreaModel *provinceModel = [[YAYIAreaModel alloc] init];
                [provinceModel setValuesForKeysWithDictionary:dict];
                provinceModel.subAreaArray = [NSMutableArray array];
                [areaArray addObject:provinceModel];
            }else if (areaID % 100 == 0) { // 市
                
                // 取出省model
                YAYIAreaModel *provinceModel = [areaArray lastObject];
                
                YAYIAreaModel *cityModel = [[YAYIAreaModel alloc] init];
                [cityModel setValuesForKeysWithDictionary:dict];
                cityModel.subAreaArray = [NSMutableArray array];
                
                [provinceModel.subAreaArray addObject:cityModel];
            }else{
            
                // 取出省model
                YAYIAreaModel *provinceModel = [areaArray lastObject];
                // 取出市model
                YAYIAreaModel *cityModel = [provinceModel.subAreaArray lastObject];
                
                YAYIAreaModel *areaModel = [[YAYIAreaModel alloc] init];
                [areaModel setValuesForKeysWithDictionary:dict];
                
                [cityModel.subAreaArray addObject:areaModel];
            }
            
            // NSLog(@"dict:%@ %@ head:%ld", areaidStr ,dict[@"name"], keyValue);
        }
        
        self.areaArray = areaArray;
        
        [self.pickerView reloadAllComponents];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}


/**
 * 获取医院数据
 */
-(void)getHospitals
{
    [self.hospitalAry removeAllObjects];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"currentPage"] = @(0);
    if (self.areaCode) {
        param[@"countycode"] = self.areaCode;
    }
    
    [YAYINetWorking getWithURL:hospital_list_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            if (dict != nil && [dict[@"data"] isEqual:NULL]) {
                return;
                
            }else{
                NSArray *data = dict[@"data"];
                
                for (NSDictionary *obj in data) {
                    YAYIChoseHospitalListModel *model = [YAYIChoseHospitalListModel new];
                    [model setValuesForKeysWithDictionary:obj];
                    [self.hospitalAry addObject:model];
                }
                
                [self.pickerView  reloadAllComponents];
            }
            
        }
        
    }];
}

#pragma mark - 点击事件
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)selectorCancelAction:(UIButton *)sender
{
    [self hideDataSelecter];
}


- (void)saveAction:(UIButton *)sender
{
    if(self.hospitalTf.text.length == 0){
        [SVProgressHUD showImage:nil status:@"\n\n请选择医院\n\n"];
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"hospitalid"] = self.hospitalID;
    
    
    [YAYINetWorking postJsonSerilizeWithURL:me_addWorkPlace param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        if (error == nil) {
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                
                [SVProgressHUD showErrorWithStatus:dict[@"message"]];

            }else{
                
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                [self back];
                if (self.refreshOperation) {
                    self.refreshOperation();
                }
                
            }
        }else{
            NSString *message = responseError[@"message"];
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

/**
 *  隐藏选择器
 */
- (void)hideDataSelecter
{
    [self.dateSelectView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(200);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.maskView.alpha = 0;
        [self.dateSelectView layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.maskView removeFromSuperview];
        [self.dateSelectView removeFromSuperview];
        self.maskView = nil;
        self.dateSelectView = nil;
    }];
}


- (void)maskViewClick:(UITapGestureRecognizer *)sender
{
//    CGPoint point = [sender locationInView:self.view];
    
    [self hideDataSelecter];
}



/**
 *  地区选择器完成按钮点击
 */
- (void)areaSlectFinishClick:(UIButton *)sender
{
    NSInteger selectRow0 = [self.pickerView selectedRowInComponent:0];
    NSInteger selectRow1 = [self.pickerView selectedRowInComponent:1];
    NSInteger selectRow2 = [self.pickerView selectedRowInComponent:2];
    
    // 取出省model
    YAYIAreaModel *provinceModel = self.areaArray[selectRow0];
    // 取出市model
    YAYIAreaModel *cityModel = provinceModel.subAreaArray[selectRow1];
    YAYIAreaModel *areaModel = cityModel.subAreaArray[selectRow2];
    
    NSString *cityCode = [NSString stringWithFormat:@"%ld", cityModel.id];
    self.areaCode = cityCode;
    
//    NSString *porvinceName = [self cutCityNameWith:province];
//    NSString *cityName = [self cutCityNameWith:city];
    self.areaTf.text = [NSString stringWithFormat:@"%@%@%@", provinceModel.name, cityModel.name, areaModel.name];
    
    [self hideDataSelecter];
}


/**
 *  地区选择器完成按钮点击
 */
- (void)hospitalSlectFinishClick:(UIButton *)sender
{
    NSInteger selectRow = [self.pickerView selectedRowInComponent:0];
    
    if (self.hospitalAry.count > 0) {
        YAYIChoseHospitalListModel *model = self.hospitalAry[selectRow];
        
        self.hospitalTf.text = model.name;
        self.hospitalID = model.id;
    }

    [self hideDataSelecter];
}

/**
 *  地区选择器
 */
- (void)areaSelect
{
    [self resignAllFistResponder];
    
    [self createAreaDataSource];
    
    // 添加覆盖层
    UIView *maskView = [[UIView alloc] init];
    maskView.backgroundColor = [UIColor blackColor];
    maskView.alpha = 0.2;
    maskView.frame = CGRectMake(0, 0, SCREEN_width, SCREEN_height);
    [self.view.window addSubview:maskView];
    self.maskView = maskView;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(maskViewClick:)];
    [maskView addGestureRecognizer:singleTap];
    
    // 创建dataselect view
    UIView *selectView = [[UIView alloc] init];
    selectView.backgroundColor = [UIColor whiteColor];
    [self.view.window addSubview:selectView];
    self.dateSelectView = selectView;
    self.dateSelectView.alpha = 0.3;
    selectView.frame = CGRectMake(0, SCREEN_height * 0.6, SCREEN_width, SCREEN_height * 0.4);
    [selectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@200);
        make.width.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(200);
        make.left.equalTo(self.view);
    }];
    
    //
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    pickerView.backgroundColor = [UIColor whiteColor];
    self.dateSelectView.alpha = 1;
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.tag = YAYIAreaSelectorTag;
    [selectView addSubview:pickerView];
    self.pickerView = pickerView;
    
    [pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(selectView);
        
    }];
    
    
    // 添加取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelBtn setTitleColor:YAYIColor(103, 176, 254) forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [selectView addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(selectorCancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@50);
        make.height.equalTo(@30);
        make.left.equalTo(pickerView).offset(15);
        make.top.equalTo(pickerView).offset(10);
    }];
    
    // 添加完成按钮
    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    finishBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [finishBtn setTitleColor:YAYIColor(103, 176, 254) forState:UIControlStateNormal];
    [finishBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [selectView addSubview:finishBtn];
    [finishBtn addTarget:self action:@selector(areaSlectFinishClick:) forControlEvents:UIControlEventTouchUpInside];
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@50);
        make.height.equalTo(@30);
        make.right.equalTo(pickerView).offset(-15);
        make.top.equalTo(pickerView).offset(10);
    }];
    
    
    
    [selectView layoutIfNeeded];
    
    [selectView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [selectView layoutIfNeeded];
    }];
}


/**
 *  医生选择器
 */
- (void)doctorSelect
{
    [self resignAllFistResponder];
    
    [self getHospitals];
    
    // 添加覆盖层
    UIView *maskView = [[UIView alloc] init];
    maskView.backgroundColor = [UIColor blackColor];
    maskView.alpha = 0.2;
    maskView.frame = CGRectMake(0, 0, SCREEN_width, SCREEN_height);
    [self.view.window addSubview:maskView];
    self.maskView = maskView;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(maskViewClick:)];
    [maskView addGestureRecognizer:singleTap];
    
    // 创建dataselect view
    UIView *selectView = [[UIView alloc] init];
    selectView.backgroundColor = [UIColor whiteColor];
    [self.view.window addSubview:selectView];
    self.dateSelectView = selectView;
    self.dateSelectView.alpha = 0.3;
    selectView.frame = CGRectMake(0, SCREEN_height * 0.6, SCREEN_width, SCREEN_height * 0.4);
    [selectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@200);
        make.width.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(200);
        make.left.equalTo(self.view);
    }];
    
    //
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    pickerView.backgroundColor = [UIColor whiteColor];
    self.dateSelectView.alpha = 1;
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.tag = YAYIHospitalSelectorTag;
    [selectView addSubview:pickerView];
    self.pickerView = pickerView;
    
    [pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(selectView);
        
    }];
    
    
    // 添加取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelBtn setTitleColor:YAYIColor(103, 176, 254) forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [selectView addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(selectorCancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@50);
        make.height.equalTo(@30);
        make.left.equalTo(pickerView).offset(15);
        make.top.equalTo(pickerView).offset(10);
    }];
    
    // 添加完成按钮
    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    finishBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [finishBtn setTitleColor:YAYIColor(103, 176, 254) forState:UIControlStateNormal];
    [finishBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [selectView addSubview:finishBtn];
    [finishBtn addTarget:self action:@selector(hospitalSlectFinishClick:) forControlEvents:UIControlEventTouchUpInside];
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@50);
        make.height.equalTo(@30);
        make.right.equalTo(pickerView).offset(-15);
        make.top.equalTo(pickerView).offset(10);
    }];
    
    
    
    [selectView layoutIfNeeded];
    
    [selectView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [selectView layoutIfNeeded];
    }];
    
    
}


#pragma mark - 工具方法
- (void)showHubWith:(NSString *)messageStr isBack:(BOOL)isBack
{
    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
    [hud setMessage:messageStr];
    [self.view.window addSubview:hud];
    [hud removeFromSuperview:YES time:1.0 isHinden:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //        if (isBack) {
        //            if (self.refreshOperation) {
        //                self.refreshOperation();
        //            }
        //            [self backAction:nil];
        //        }
        
    });
    
}


/**
 *  截取城市名，如杭州市，截取成杭州
 */
- (NSString *)cutCityNameWith:(NSString *)city
{
    // 需要剪掉的尾部
    NSArray *tailStrArray = @[@"市", @"省", @"自治区", @"特别行政区"];
    
    NSString *cityName = city;
    if (cityName.length > 0) {
        for (NSString *tail in tailStrArray) {
            NSRange range = [city rangeOfString:tail];
            if (range.location != NSNotFound) {
                cityName = [city substringToIndex:city.length - tail.length];
            }
        }
    }
    return cityName;
}


- (NSMutableAttributedString *)setCurLocation:(NSString *)areaStr city:(NSString *)city isAutoPostion:(BOOL)isAutoPostion
{
    NSString *areaName = areaStr;
    if (areaStr.length > 0) {
        NSString *areaTail = [areaStr substringFromIndex:areaStr.length - 1];
        if ([areaTail isEqualToString:@"省"]) {
            areaName = [areaStr substringToIndex:areaStr.length - 1];
        }
    }
    
    NSString *cityName = city;
    if (cityName.length > 0) {
        NSString *cityTail = [city substringFromIndex:city.length - 1];
        if ([cityTail isEqualToString:@"市"]) {
            
            cityName = [city substringToIndex:city.length - 1];
        }
    }
    
    NSString *autoPostionStr = @"";
    if (isAutoPostion) {
        autoPostionStr = @"(自动定位)";
        NSString *showStr = [NSString stringWithFormat:@"%@  %@  %@", areaName, cityName, autoPostionStr];
        
        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:showStr];
        [attriString addAttribute:NSForegroundColorAttributeName
                            value:(id)YAYIColor(146, 146, 146).CGColor
                            range:NSMakeRange(showStr.length - 6, 6)];
        [attriString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(showStr.length - 6, 6)];
        
        return attriString;
    }else{
    }
    
    
    //    self.address = [NSString stringWithFormat:@"%@  %@", areaName, cityName];
    
    return nil;
}

#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YAYIAddHospitalCell *cell = [YAYIAddHospitalCell cellWith:tableView];
    cell.textLabel.text = self.items[indexPath.row];
    cell.tf.delegate = self;
    cell.tf.tag = indexPath.row;
    
    switch (indexPath.row) {
        case 0:{
            self.areaTf = cell.tf;
            NSDictionary *locDic = [[NSUserDefaults standardUserDefaults] dictionaryForKey:YAYILocationKey];
            
            if (locDic) {
                NSString *provinceName = locDic[@"administrativeArea"];
                NSString *cityName = locDic[@"locality"];
                
                self.areaCode = locDic[@"areacode"];
                cell.tf.attributedText = [self setCurLocation:provinceName city:cityName isAutoPostion:YES];
            }
            break;
        }
        case 1:
            
            self.hospitalTf = cell.tf;
            break;
        default:
            break;
    }
    
    return cell;
}


#pragma mark textfield代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (0 == textField.tag) {
        [self resignAllFistResponder];
        
        [self areaSelect];
        return NO;
        
    }else if(1 == textField.tag) {
        

        [self doctorSelect];
        return NO;
    }
    
    
    return YES;
}


#pragma mark pickerView代理
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (pickerView.tag == YAYIHospitalSelectorTag) {
        return 1;
    }
    return 3;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if (pickerView.tag == YAYIHospitalSelectorTag) {
        return self.hospitalAry.count;
    }
    
    if (0 == component) {
        
        return self.areaArray.count;
    }else if(1 == component){
        
        NSInteger row0 = [pickerView selectedRowInComponent:0];
        
        YAYIAreaModel *prvinceModel = self.areaArray[row0];
        
        return prvinceModel.subAreaArray.count;
    }else if(2 == component){
        
        NSInteger row0 = [pickerView selectedRowInComponent:0];
        NSInteger row1 = [pickerView selectedRowInComponent:1];
        
        YAYIAreaModel *provinceModel = self.areaArray[row0];
        
        if (provinceModel.subAreaArray.count == 0) {
            return 0;
        }
        
        YAYIAreaModel *cityModel = provinceModel.subAreaArray[row1];
        return cityModel.subAreaArray.count;
    }
    
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == YAYIHospitalSelectorTag) {
        YAYIChoseHospitalListModel *model = self.hospitalAry[row];
        return model.name;
    }
    
    if (0 == component) {
        
        YAYIAreaModel *provinceModel = self.areaArray[row];
        return provinceModel.name;
    }else if(1 == component){
        
        NSInteger row0 = [pickerView selectedRowInComponent:0];
        
        YAYIAreaModel *prvinceModel = self.areaArray[row0];
        YAYIAreaModel *cityModel = prvinceModel.subAreaArray[row];
        
        return cityModel.name;
    }else if (2 == component){
    
        NSInteger row0 = [pickerView selectedRowInComponent:0];
        NSInteger row1 = [pickerView selectedRowInComponent:1];
        
        YAYIAreaModel *prvinceModel = self.areaArray[row0];
        YAYIAreaModel *cityModel = prvinceModel.subAreaArray[row1];
        YAYIAreaModel *areaModel = cityModel.subAreaArray[row];
        
        return areaModel.name;
    }
    
    return @"test";
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView.tag == YAYIHospitalSelectorTag) {
        
        return;
    }
    
    if (0 == component) {
        
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
        
//        [pickerView ];
//        [pickerView selectRow:0 inComponent:1 animated:YES];
//        [pickerView selectRow:0 inComponent:2 animated:YES];
    }else if(1 == component){
        
        [pickerView reloadComponent:2];
//        [pickerView selectRow:0 inComponent:2 animated:YES];
    }else if (2 == component){
        
        
    }
}


@end
